#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/5/26 16:19
# @Author  : TomNewChao
# @File    : filter-publish-event.py
# @Description :

import os
import sys
import logging

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, "utils"))
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")

from utils.gitcode_helper import GitCodeHelper
from utils.parse_params import parse_repo_info_by_webhook_payload
from utils.common import func_retry


class FilterPublishEventHelper:
    _comment = "/publish"

    def __init__(self, owner, repo, pr_number, token):
        self._git_helper = GitCodeHelper(owner, repo, pr_number, token)

    @func_retry()
    def check_publish(self):
        comments = self._git_helper.get_comment_by_pr_id()
        for comment in comments:
            if comment["body"].startswith(self._comment):
                return True
        return False

    def create_comment(self, comment):
        self._git_helper.create_comment({"body": comment})


def main():
    token = os.getenv("gitcode_token")
    if not token:
        logging.info("Error:env git_code_token must not be empty")
        sys.exit(-1)
    owner, repo, _, pr_number, _ = parse_repo_info_by_webhook_payload()
    filter_publish_event = FilterPublishEventHelper(owner, repo, pr_number, token)
    if filter_publish_event.check_publish():
        sys.exit(0)
    logging.info("Error: Not Receive publish event.")
    sys.exit(-1)


if __name__ == '__main__':
    main()
